//
//  ControllerViewController.m
//  EaseMob
//
//  Created by wwj on 16/5/26.
//  Copyright © 2016年 wfw. All rights reserved.
//

#import "ContactsViewController.h"
#import "UIBarButtonItem+Extend.h"
#import "AddContactViewController.h"
#import "ChatViewController.h"
#import <SVProgressHUD.h>
#import <EMSDK.h>
#import <Masonry.h>

@interface ContactsViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) UISearchBar *searchBar;
@property (weak, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;
@end

@implementation ContactsViewController

static NSString *const ID = @"ID";

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupTitleBar];
    [self setupSearchBar];
    [self setupTableView];
    
    [self getDataArray];
}

- (void)setupTitleBar{
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"TabBar4" highIcon:@"TabBar4Sel" target:self action:@selector(onClickAdd)];
}

- (void)onClickAdd{
    AddContactViewController *addContactVC = [[AddContactViewController alloc] init];
    [self.navigationController pushViewController:addContactVC animated:YES];
}

- (void)setupSearchBar{
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.placeholder = @"搜索";
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [self.view addSubview:searchBar];
    self.searchBar = searchBar;
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(64);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
    }];
}

- (void)setupTableView{
    UITableView *tableView = [[UITableView alloc] init];
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchBar.mas_bottom).offset(0);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatViewController *chatVC = [[ChatViewController alloc] init];
    chatVC.conversaionID = self.dataArray[indexPath.row];
    chatVC.chatType = EMConversationTypeChat;
    
    [self.navigationController pushViewController:chatVC animated:YES];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
             EMError *error = [[EMClient sharedClient].contactManager deleteContact:self.dataArray[indexPath.row]];
            if (!error) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [self.dataArray removeObjectAtIndex:indexPath.row];
                    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                }];
            }
        }];
    }
}

- (void)reloadContactData{
    [self getDataArray];
}

#pragma mark 获取好友列表
- (void)getDataArray{
    //从数据库获取
    self.dataArray = [[EMClient sharedClient].contactManager getContactsFromDB].mutableCopy;
    if (self.dataArray.count == 0) {
        //从服务器获取
        [self getDataFromService];
    }else{
        [self.tableView reloadData];
    }
}

#pragma mark 从服务器获取好友列表
- (void)getDataFromService{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.dataArray = [[EMClient sharedClient].contactManager getContactsFromServerWithError:nil].mutableCopy;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}
@end
